package com.ciwong.epaper.modules.dictation.ui;

import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.dictation.bean.DictationAnswerInfo;
import com.ciwong.epaper.modules.epaper.util.EpaperJumpManager;
import com.ciwong.epaper.modules.epaper.util.RepeatKeyUtil;
import com.ciwong.epaper.modules.evaluate.bean.WordDetail;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.libs.audio.play.AudioPlayer;
import com.ciwong.libs.audio.play.OnPlayListener;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.widget.CWToast;
import com.ciwong.mobilelib.utils.ToastUtil;

import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;

public class DictationActivity extends BaseDictationActivity {


    @Override
    public void playNext() {//下一个
        try {
            if (isRepeatWord) {
                String wordAnswer = mEtAnswer.getText().toString();
                reListenWorkAnswer.setWordAnswer(wordAnswer);
                reListenWorkAnswer.setRight(pigai(wordAnswer));
                if (currentListenAndRepeatIndex >= 0 && currentListenAndRepeatIndex < words.size()) {
                    reListenWorkAnswer.setPretations(words.get(currentListenAndRepeatIndex).getPretations());
                }
            } else {
                saveAnswer();
            }
            currentListenAndRepeatIndex++;
            refreshWordUi(currentListenAndRepeatIndex);
            if (currentListenAndRepeatIndex >= words.size()) {
                allComplete();
            } else {
                play(false);
            }
        } catch (Exception e) {

        }


    }

    @Override
    public void playForword() {//上一个
        saveAnswer();
        currentListenAndRepeatIndex--;
        refreshWordUi(currentListenAndRepeatIndex);
        play(false);
    }

    @Override
    public void playRepeat() {//重播
        play(true);
    }

    @Override
    public void play(boolean isPlayRepeat) {//开始
        mHandler.removeCallbacks(mSecondPlayRunnable);
        isFirstPlay = true;
        setNo(currentListenAndRepeatIndex + 1, words.size());
        //如果是点击重播按钮，不改变EditText的内容
        if (!isPlayRepeat) {
            setAnswerToEditext();
        }


        startStudy();
    }

    private void setAnswerToEditext() {
        try {
            if (isRepeatWord) {
                if (reListenWorkAnswer != null) {
                    mEtAnswer.setText(reListenWorkAnswer.getWordAnswer());
                    mEtAnswer.setSelection(reListenWorkAnswer.getWordAnswer().length());

                }
            } else {
                if (answerRecorders != null && answerRecorders.size() > currentListenAndRepeatIndex) {
                    String wordAnswer = answerRecorders.get(currentListenAndRepeatIndex).getWordAnswer();
                    if (!TextUtils.isEmpty(wordAnswer)) {
                        mEtAnswer.setText(wordAnswer);
                        mEtAnswer.setSelection(wordAnswer.length());

                    } else {
                        mEtAnswer.setText("");
                    }
                } else {
                    mEtAnswer.setText("");
                }
            }

        } catch (Exception e) {

        }

    }

    @Override
    public void pause() {//暂停
        operateStatus = OPERATE_STATUS_STOP;
        isFirstPlay = false;
        AudioPlayer.getInstance().stop();
        mHandler.removeCallbacks(mSecondPlayRunnable);
        cancelTimer();
        showRePlayImageView();
    }

    @Override
    protected void onPause() {
        super.onPause();
        pause();
    }

    public void playWord() {//播放单词
        try {
            synchronized (words)//播放原音
            {
                if (words == null) {
                    return;
                }
                if (currentListenAndRepeatIndex >= words.size()) {
                    return;
                }
                operateStatus = OPERATE_STATUS_NORMAL;
                final WordDetail unitWord = words.get(currentListenAndRepeatIndex);

                String url = ESystem.formatPath(unitWord.getWordFile());
                CWLog.d(TAG, "url:" + url);
                if (TextUtils.isEmpty(url)) {
                    int errorResId = R.string.speech_word_url_invalid_1;
                    CWToast.centerSquareError(DictationActivity.this, errorResId).show();
                    if (isRepeatWord) {//重读
                        return;
                    }
                } else {

                    AudioPlayer.getInstance().setOnPlayListener(listener).play(url,
                            true);
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M && EApplication.getInstance().mPlayerspeed != 1.0f) {
                        MediaPlayer mMediaPlayer = AudioPlayer.getInstance().getMediaPlayer();
                        if (mMediaPlayer != null) {
                            try {
                                PlaybackParams params = mMediaPlayer.getPlaybackParams().setSpeed(EApplication.getInstance().mPlayerspeed);
                                if (params != null) {
                                    mMediaPlayer.setPlaybackParams(params);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {

        }


    }


    //倒计时结束   自动开始做题流程
    @Override
    public void close() {
        startTimer();
        play(false);
    }


    @Override
    public void allComplete() {//完成
        if (isRepeatWord) {
            compelteRedoDictation();
        } else {
            CWSys.setSharedBoolean(mUuid + HAS_COMPLETED_WORK, true);
            EpaperJumpManager.jumpToDictaionRedoAndResult(R.string.go_back, this, words, mDownLoadInfo, mModule, position, answerRecorders, mResourceName, getAnswer(), mUuid, workLong, mWorkContents, effectiveDate);
            finish();
        }

    }


    public boolean pigai(String wordAnswer) {
        try {
            String w = "";
            if (isRepeatWord) {
                w = words.get(0).getWords();
            } else {
                w = words.get(currentListenAndRepeatIndex).getWords();
            }


            StringBuffer stringBuffer = new StringBuffer();
            StringBuffer stringBuffer1 = new StringBuffer();
            for (int i = 0; i < w.length(); i++) {
                if (Character.isDigit(w.charAt(i)) || Character.isLetter(w.charAt(i))) {
                    stringBuffer.append(w.charAt(i));

                }
            }
            for (int i = 0; i < wordAnswer.length(); i++) {
                if (Character.isDigit(wordAnswer.charAt(i)) || Character.isLetter(wordAnswer.charAt(i))) {
                    stringBuffer1.append(wordAnswer.charAt(i));
                }
            }

            if (stringBuffer.toString().toLowerCase().equals(stringBuffer1.toString().toLowerCase())) {
                return true;
            }
        } catch (Exception e) {
            e.getStackTrace();
            return false;
        }


        return false;
    }

    @Override
    public void saveAnswer() {
        try {
            String wordAnswer = mEtAnswer.getText().toString();
            WordDetail mWordDetail = null;
            Iterator<DictationAnswerInfo> iterator = answerRecorders.iterator();
            if (words == null) {
                return;
            }
            if (currentListenAndRepeatIndex >= 0 && currentListenAndRepeatIndex < words.size()) {
                mWordDetail = words.get(currentListenAndRepeatIndex);
            }
            if (mWordDetail == null) {
                return;
            }
            while (iterator.hasNext()) {
                DictationAnswerInfo l = iterator.next();
                if (l.getwId().equals(mWordDetail.getwId())) {
                    l.setWordAnswer(wordAnswer);
                    l.setRight(pigai(wordAnswer));
                    l.setPretations(mWordDetail.getPretations());
                }
            }
            String key = RepeatKeyUtil.getWordRepeatAnswerListKey(mDownLoadInfo, mModule, position, intentWorkId, mUuid);
            SerializableManager.getInstance().serialize(key, answerRecorders);
            CWSys.setSharedInt(getSaveTime(), workLong);
        } catch (Exception e) {
            e.getStackTrace();
        }

    }

    //开始学习
    public void startStudy() {
        try {
            if (words == null) {
                return;
            }
            if (isRepeatWord) {
                operateStatus = OPERATE_STATUS_NORMAL;
                if (operateStatus == OPERATE_STATUS_STOP) {

                    return;
                }
            } else {
                //答案记录
                if (answerRecorders == null) {
                    answerRecorders = new CopyOnWriteArrayList<>();
                }
                operateStatus = OPERATE_STATUS_NORMAL;
                if (operateStatus == OPERATE_STATUS_STOP) {
                    return;
                }
                //切换单词显示页面
                cacheListenAndRepeatIndex = currentListenAndRepeatIndex;
                if (currentListenAndRepeatIndex >= words.size()) {//暂停时候  最后一题的时候完成试卷
                    //已经完成作业
                    allComplete();
                    return;
                }
                //先添加纪录
                if (answerRecorders.size() <= currentListenAndRepeatIndex) {
                    DictationAnswerInfo ar = new DictationAnswerInfo();
                    ar.setwId(words.get(currentListenAndRepeatIndex).getwId());
                    ar.setWord(words.get(currentListenAndRepeatIndex).getWords());
                    ar.setWordAnswer("");
                    answerRecorders.add(ar);
                }
            }

            startTime = System.currentTimeMillis();
            playWord();
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    private Runnable mSecondPlayRunnable = new Runnable() {

        @Override
        public void run() {
            isFirstPlay = false;
            playWord();
        }
    };

    private OnPlayListener listener = new OnPlayListener() {
        @Override
        public void stop(Object mp3) {
            if (isFirstPlay) {
                mHandler.postDelayed(mSecondPlayRunnable, 2000);

            }

            setPlayBtnState(false, isFirstPlay);

        }

        @Override
        public void onPlayStart(Object mp3) {
            setPlayBtnState(true, isFirstPlay);
        }

        @Override
        public void onReadPlayer(long duration, Object mp3) {

        }

        @Override
        public void onError(int errorCode, final Object tag) {
            Log.e(TAG, "播放音频失败 onError: " + errorCode);
            mHandler.removeCallbacks(mSecondPlayRunnable);
            ToastUtil.INSTANCE.toastCenter(DictationActivity.this, "播放音频失败", R.mipmap.ic_error);
            isFirstPlay = true;
            setPlayBtnState(false, false);
        }

        @Override
        public void onBuffer(Object mp3, long progress, long total) {

        }

        @Override
        public void onPlaying(long arg0, long arg1) {

        }

    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AudioPlayer.getInstance().stop();
        mHandler.removeCallbacks(mSecondPlayRunnable);
    }

}
